package socket

import (
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/core/mysql"
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"time"
)

// 读消息
func read(conn *websocket.Conn) {
	defer conn.Close()

	for {
		mType, msg, err := conn.ReadMessage()
		if err != nil {
			if mType == -1 {
				//客户端断开连接
				delete(localConnections, conn.RemoteAddr().String())
				return
			}

			fmt.Println("read:", err, mType)
			return
		}

		//处理消息
		u := &models.Message{}
		err = json.Unmarshal(msg, u)
		if err != nil {
			//消息解析错误，向客户端发消息
			write(conn, "消息解析失败，err："+err.Error())
			continue
		}

		//将消息写入到数据库
		u.CreatedAt = time.Now().Format("2006-01-02 15:04:05")
		res := mysql.MysqlClient.Create(u)
		if res.Error != nil {
			write(conn, "消息存储失败，err："+err.Error())
			continue
		}
	}
}
